package com.wx.lock.redis;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author wx
 * @Description: 具体业务
 * @date 2018/12/1
 */
public class Service {
    private static JedisPool pool = null;
    private DistributedLock distributedLock = new DistributedLock(pool);
    private int n = 500;
    static {
        JedisPoolConfig config = new JedisPoolConfig();

        // 设置最大连接数
        config.setMaxTotal(50);
        // 设置最大空闲数
        config.setMaxIdle(5);
        // 设置最大等待时间
        config.setMaxWaitMillis(1000 * 5);
        // 在获取连接的时候检查有效性, 默认false
        config.setTestOnBorrow(true);
        pool = new JedisPool(config, "127.0.0.1", 6379, 5000);

    }



    /**
     * @methodName: seckill
     * @author: wx
     * @description: 具体操作业务
     * @param
     * @date: 2018/12/1
     * @return: void
     */
    public void seckill() {
        // 获取锁，并返回锁的vlaue
        String indentifier = distributedLock.lockWithTimeout("resource", 5000, 1000);
        if (indentifier != null) {
            System.out.println(Thread.currentThread().getName() + "获得了锁");
            System.out.println(--n);
            //释放锁
            distributedLock.releaseLock("resource", indentifier);
        } else {
            System.out.println(Thread.currentThread().getName() + "获取锁超时,放弃获取锁");
        }
    }
}
